package com.frontop.modules.controller;

import com.alibaba.fastjson.JSONObject;
import com.frontop.common.util.JwtUtil;
import com.frontop.common.util.ResultJsonUtil;
import com.frontop.constan.Oauth2TokenDto;
import com.frontop.modules.service.TUserService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * @author YangBoos
 * @title: AuthController
 * @projectName frontop-cloud
 * @description: 认证接口
 */
@RestController
@RequestMapping
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private TUserService tUserService;


    /**
     * 获取token登录或者刷新token
     *
     * 刷新：http://localhost:10800/oauth/token?grant_type=refresh_token&refresh_token=token内容&client_id=app-client&client_secret=client-secret-8888
     *
     * @param principal
     * @param params
     * @return
     * @throws HttpRequestMethodNotSupportedException
     */
    @ApiOperation(value = "Oauth2获取token",consumes = "application/json;charset=UTF-8")
    @RequestMapping(value = "/postAccessToken", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", value = "Oauth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", value = "Oauth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", value = "登录用户名"),
            @ApiImplicitParam(name = "password", value = "登录密码")
    })
    public ResultJsonUtil<Object> postAccessToken(Principal principal, @RequestParam Map<String, String> params) throws HttpRequestMethodNotSupportedException {
        params.put("scope","all");
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, params).getBody();
        List<String> ju = tUserService.getUserAllJurisdiction(params.get("username"));
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(JSONObject.toJSONString(ju)).build();
        ResultJsonUtil<Object> a = new ResultJsonUtil().success(oauth2TokenDto);

        return  a;
    }



}